package com.starblink.mine.personhome.ui.wishlist.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.ApolloModelExt.isWishlistOpen
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.basic.log.SKLogger
import com.starblink.basic.util.FormatUtils
import com.starblink.mine.R
import com.starblink.mine.databinding.FragmentWishlistBinding
import com.starblink.mine.personhome.ui.SharedViewModel
import com.starblink.mine.personhome.ui.wishlist.ui.wishlistboards.ui.WishlistBoardsFragment
import com.starblink.mine.personhome.ui.wishlist.ui.wishlistitems.ui.WishlistItemsFragment
import com.starblink.rocketreserver.fragment.AccountF

/**
 * 个人首页-客态-Wishlist子页
 */
class WishlistFragment : BaseTVMFragment<FragmentWishlistBinding, WishlistVM>() {
    var accountDeleted: Boolean = false
    var accountId: String = ""
    private val sharedViewModel by activityViewModels<SharedViewModel>()

    companion object {
        private const val TAG = "WishlistFragment"
        const val PAGE_ITEMS = 0
        const val PAGE_BORADS = 1

        fun newInstance(accountId: String, accountDeleted: Boolean = false) =
            WishlistFragment().apply {
                arguments = bundleOf(
                    MineManager.KEY_USER_ID to accountId,
                    MineManager.KEY_ACCOUNT_DELETED to accountDeleted
                )
            }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentWishlistBinding {
        return FragmentWishlistBinding.inflate(inflater, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SKLogger.e("dss", "WishlistFragment-onCreate")
    }

    override fun initData() {
        arguments?.run {
            accountId = getString(MineManager.KEY_USER_ID, "")
            accountDeleted = getBoolean(MineManager.KEY_ACCOUNT_DELETED, false)
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        // 客态-如果账户已删除，仅显示Empty页面即可
        if (accountDeleted) {
            viewBinding.state.onEmpty {
                val tvMsg1 = findViewById<TextView>(R.id.msg2)
                tvMsg1.text =
                    getString(com.starblink.basic.style.R.string.wishlist_account_deleted_hint)
            }
            viewBinding.state.showEmpty()
            return
        }

        initContentView()
        initStateView()
    }

    private fun initContentView() {
        viewBinding.tabItems.setOnClickListener {
            if (viewBinding.tabItems.isSelected) {
                return@setOnClickListener
            }
            setTabSelected(PAGE_ITEMS)
            viewBinding.viewPager.currentItem = PAGE_ITEMS
        }
        viewBinding.tabBoards.setOnClickListener {
            if (viewBinding.tabBoards.isSelected) {
                return@setOnClickListener
            }
            setTabSelected(PAGE_BORADS)
            viewBinding.viewPager.currentItem = PAGE_BORADS
        }

        viewBinding.viewPager.adapter = object : FragmentStateAdapter(requireActivity()) {
            override fun createFragment(position: Int): Fragment {
                return when (position) {
                    PAGE_ITEMS -> WishlistItemsFragment.newInstance(accountId)
                    else -> WishlistBoardsFragment.newInstance(accountId)
                }
            }

            override fun getItemCount(): Int {
                return 2
            }
        }
        viewBinding.viewPager.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                setTabSelected(position)
            }
        })
//        viewBinding.viewPager.isUserInputEnabled = false//禁止左右滑动

        // 默认选中第一项
        viewBinding.tabItems.isSelected = true
//        viewBinding.viewPager.currentItem = PAGE_ITEMS
    }

    private fun setTabSelected(position: Int) {
        if (position == PAGE_ITEMS) {
            viewBinding.tabItems.isSelected = true
            viewBinding.tabBoards.isSelected = false
        } else {
            viewBinding.tabBoards.isSelected = true
            viewBinding.tabItems.isSelected = false
        }
    }

    private fun initStateView() {
        viewBinding.state.onEmpty {
            val tvMsg1 = findViewById<TextView>(R.id.msg2)
            if (it is AccountF) {
                if (it.deleted == true) {
                    tvMsg1.text =
                        getString(com.starblink.basic.style.R.string.wishlist_account_deleted_hint)
                } else if (!it.isWishlistOpen()) {
                    tvMsg1.text = getString(com.starblink.basic.style.R.string.wishlist_not_visible)
                }
            }
        }

        sharedViewModel.userInfoLiveData.observe(this) {
            // 客态-用户信息加载完毕
            // 如果用户账户已删除或用户的Wishlist不允许查看，显示错误提示
            // 否则，显示内容视图
            if (it.deleted == true || !it.isWishlistOpen()) {
                viewBinding.state.showEmpty(it)
            } else {
                viewBinding.state.showContent()
            }
        }
    }

    override fun startObserve() {
        // 客态-如果账户已删除，仅显示Empty页面即可
        if (accountDeleted) {
            return
        }

        // 更新Tab数量
        sharedViewModel.userCountDataLiveData.observe(this) {
//            SKLogger.e("dss", "sharedViewModel.userCountDataLiveData=${it}")
            viewBinding.tabItems.text =
                "Items • ${FormatUtils.formatAccountDataNum(it.collectionCount)}"
            viewBinding.tabBoards.text =
                "Boards • ${FormatUtils.formatAccountDataNum(it.wishListCount)}"
        }

        // 客态-默认显示加载中，等待用户信息加载完毕
        viewBinding.state.showLoading()
    }
}